package org.example.jwt1.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.jwt1.entity.ResponseData;
import org.example.jwt1.entity.ResponseResult;
import org.example.jwt1.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class JwtLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private HttpServletResponse httpServletResponse;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String token  = JwtUtils.generateToken(authentication);
        response.setContentType("application/json;charset=utf-8");
        ResponseResult sr = new ResponseResult();
        sr.setCode(200);
        sr.setAuthorization(token);
        sr.setFlag(true);
        String s = objectMapper.writeValueAsString(sr);
        httpServletResponse.getWriter().write(s);
    }
}
